package ddbs;

public class LocalWork extends AbsWork implements Runnable{
    long startTime;
    Data data = null;
    public Peer assignto;
    public DataSet ds = null;
    public String imsql = null;

    protected LocalWork() {
    }
    public Peer getPeer() {
        return null;
    }
    protected String formalSQL() {
        return null;
    }

    protected void handleLocal() {
    }

    protected MSG toMSG() {
        return null;
    }

    protected void handleResponse(MSG msg) {
    }

    public String getStatus() {
        return "LocalWork";
    }

    public void sendWorkFailed() {
        this.data = null;
        done();
    }

    public DataSet getDataSet() {
        return ds;
    }

    protected void queryDatabaseReal() {
        String sql = formalSQL();
        this.data = DatabaseQuery.query(sql);
        done();
    }
    protected void queryDatabase() {
        Thread t = new Thread(this);
        t.start();
    }

    protected void dealWith() {
        startTime = System.currentTimeMillis();
        if (assignto.IsSelf()) {
            handleLocal();
        } else {
            assignto.sendWork(this);
        }
    }

    public void assignTo(Peer p) {
        this.assignto = p;
    }

    public void setImsql(String imsql) {
        this.imsql = imsql;
    }

    public void show(PeerMgr mgr) {
        System.out.println("=========================== show work");
        System.out.println("#" + getId() + ": " + this.getStatus() + " "
                + this.imsql);
        this.getDataSet().show();
        MSG msg = this.toMSG();
        msg.show();
        if (this.getStatus() == "swork") {
            Work sw = new SimpleWorkCreater(mgr).fromMSG(msg);
            System.out.println(sw.formalSQL());
        } else {
            BinWork bw = new BinWorkCreater(mgr).fromMSG(msg);
            System.out.println("w1:" + bw.w1.toString());
            System.out.println("w2:" + bw.w2.toString());
        }
        System.out.println("=========================== show work end");

    }

    public String toString() {
        return "#"+id+" "+getStatus()+" "+toMSG().content;
    }
    @Override
    public void run() {
        queryDatabaseReal();
    }
}
